package com.file.parser;

import com.file.bo.IIT;
import com.file.bo.IITTran;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.parser.traprange.PDFTableExtractor;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.*;
import technology.tabula.detectors.NurminenDetectionAlgorithm;
import technology.tabula.extractors.BasicExtractionAlgorithm;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class IITPdfParser extends BaseDecryptPdfParser {

    private static final Integer IIT_HEADER_LINE_NUMBER = 10;
    private static final Integer IIT_FOOTER_LINE_NUMBER = 8;

    public ResponseData<String> parseIITPdfToJson(String daId, String filePath, String pdfPassword) {
        log.info("parseIITPdfToJson started, daId:{}, pdfPassword:{}", daId, pdfPassword);
        String json = null;

        try {
            IIT iit = parseIITPdf(filePath, pdfPassword);
            json = JsonUtils.convertObjectToJson(iit);
            doAlert(daId, iit);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "parseIITPdfToJson failed", e);
            return new ResponseData<String>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseIITPdfToJson completed, daId:{}, pdfPassword:{}", daId, pdfPassword);
        return new ResponseData<String>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }


    public IIT parseIITPdf(String filePath, String pdfPassword) {
        String pdfHeaderText = parsePdfHeaderText(filePath, pdfPassword);
        IIT iit = parseIITHeader(pdfHeaderText);
        List<IITTran> iitTrans = new ArrayList<>();//NOSONAR
        // 适配2025新版文件
        if (pdfHeaderText.contains("纳 税 ⼈ 名 称 :")) {
            iitTrans = parseIITTrans(filePath, pdfPassword);
        } else {
            iitTrans = parseIITTransNew(filePath, pdfPassword);
        }


        iit.setIitTrans(iitTrans);
        return iit;
    }

    public IIT parseIITHeader(String pdfHeaderText) {
        IIT iit = new IIT();

        String recordPeriod, taxpayerName, taxpayerIdNo, IdCardType, idNo, amountUnit, issueDate;

        if (pdfHeaderText.contains("纳 税 ⼈ 名 称 :")) {
            recordPeriod = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("记 录 期 间 :") + 9, pdfHeaderText.indexOf("纳 税 ⼈ 名 称 : ")).trim();
            taxpayerName = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("纳 税 ⼈ 名 称 :") + 11, pdfHeaderText.indexOf("纳税⼈识别号:")).trim();
            taxpayerIdNo = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("纳税⼈识别号:") + 7, pdfHeaderText.indexOf("⾝份证件类型:")).trim();
            IdCardType = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("⾝份证件类型:") + 7, pdfHeaderText.indexOf("⾝份证件号码:")).trim();
            idNo = pdfHeaderText.substring(pdfHeaderText.indexOf("⾝份证件号码:") + 7, pdfHeaderText.indexOf("⾦额单位:"))
                    .trim();
            amountUnit = pdfHeaderText.substring(pdfHeaderText.indexOf("⾦额单位:") + 5, pdfHeaderText.indexOf("申报⽇期"))
                    .trim();
            issueDate = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("开具时间：") + 5, pdfHeaderText.indexOf("本凭证不作为纳税⼈记账")).trim();
        } else {
            // 适配表头编码变更用例
            pdfHeaderText = pdfHeaderText.replaceAll(" ", "");
            recordPeriod = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("记录期间:") + 5, pdfHeaderText.indexOf("纳税人名称:")).trim();
            taxpayerName = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("纳税人名称:") + 6, pdfHeaderText.indexOf("纳税人识别号:")).trim();
            taxpayerIdNo = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("纳税人识别号:") + 7, pdfHeaderText.indexOf("身份证件类型:")).trim();
            IdCardType = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("身份证件类型:") + 7, pdfHeaderText.indexOf("身份证件号码:")).trim();
            idNo = pdfHeaderText.substring(pdfHeaderText.indexOf("身份证件号码:") + 7, pdfHeaderText.indexOf("金额单位:"))
                    .trim();
            amountUnit = pdfHeaderText.substring(pdfHeaderText.indexOf("金额单位:") + 5, pdfHeaderText.indexOf("申报日期"))
                    .trim();
            issueDate = pdfHeaderText
                    .substring(pdfHeaderText.indexOf("开具时间：") + 5, pdfHeaderText.indexOf("本凭证不作为纳税人记账")).trim();
        }

        iit.setRecordPeriod(recordPeriod);
        iit.setTaxpayerName(taxpayerName);
        iit.setTaxpayerIdNo(taxpayerIdNo);
        iit.setIdCardType(IdCardType);
        iit.setIdNo(idNo);
        iit.setAmountUnit(amountUnit);
        iit.setIssueDate(issueDate);

        return iit;
    }

    public String parseTransToText(String filePath, String pdfPassword) {
        PDFTableExtractor extractor = (new PDFTableExtractor()).setSource(filePath, pdfPassword);
        int pdfPageNumber = getPdfPageNumber(filePath, pdfPassword);

        for (int k = 0; k < pdfPageNumber; k++) {
            // 对第一页处理
            int[] skipLinesIndexes1;
            if (k == 0) {
                //第一页多一行，单位，其它页少一行这个
                skipLinesIndexes1 = new int[IIT_HEADER_LINE_NUMBER];
                for (int i = 0; i < IIT_HEADER_LINE_NUMBER; i++) {
                    skipLinesIndexes1[i] = i;
                }
            } else {
                skipLinesIndexes1 = new int[IIT_HEADER_LINE_NUMBER - 1];
                for (int i = 0; i < IIT_HEADER_LINE_NUMBER - 1; i++) {
                    skipLinesIndexes1[i] = i;
                }
            }
            extractor.exceptLine(k, skipLinesIndexes1);

            int[] skipLinesIndexes2 = new int[IIT_FOOTER_LINE_NUMBER];
            for (int j = 0; j < IIT_FOOTER_LINE_NUMBER; j++) {
                skipLinesIndexes2[j] = -(j + 1);
            }
            extractor.exceptLine(k, skipLinesIndexes2);
        }

        return extractPdfToText(extractor);
    }


    private List<List<String>> parseFileToRowList(String filePath, String pdfPwd) {
        //页面所有table的记录，每一个元素代表下面一条记录cellList
        List<List<String>> rowList = new ArrayList<>();

        // 1. 读取文件
        File pdf = new File(filePath);

        // 2. pdfbox读取PDDocument
        try (PDDocument pdfDocument = PDDocument.load(pdf, pdfPwd)) {

            // 3. tabula新建ObjectExtractor和NurminenDetectionAlgorithm，同时准备接收表格Rectangle的结构
            ObjectExtractor objectExtractor = new ObjectExtractor(pdfDocument);
            NurminenDetectionAlgorithm detectionAlgorithm = new NurminenDetectionAlgorithm();
            Map<Integer, List<Rectangle>> detectedTables = new HashMap<>();

            // 4. 获取每页的PageIterator
            PageIterator pages = objectExtractor.extract();

            // 5. 解析每页的Rectangle(table的位置)
            while (pages.hasNext()) {
                Page page = pages.next();
                List<Rectangle> tablesOnPage = detectionAlgorithm.detect(page);
                if (tablesOnPage.size() > 0) {
                    detectedTables.put(page.getPageNumber(), tablesOnPage);
                }
            }

            // 6.通过table位置获取表格具体内容
            BasicExtractionAlgorithm bea = new BasicExtractionAlgorithm();

            // 如果单页pdf中有多个表格，则解析出来的List<Rectangle>会有多个对象
            for (Map.Entry<Integer, List<Rectangle>> entry : detectedTables.entrySet()) {
                Page page = objectExtractor.extract(entry.getKey());
                // 默认每页只有一个表格，因此获取第0个rectangle/
                Rectangle rectangle = null; //NOSONAR
                List<Rectangle> rectangleList = entry.getValue();
                for (Rectangle r : rectangleList) {
                    double rectangleHeight = r.getHeight();
                    if (Double.compare(rectangleHeight, 0) > 0) {
                        rectangle = r;
                        break;
                    }
                }
                if (rectangle == null) {
                    throw new RuntimeException("rectangle is null.");
                }
                rectangle.setBottom(rectangle.getBottom() + 900);
                rectangle.setRight(rectangle.getBottom() + 150);

                Page area = page.getArea(rectangle);
                List<Table> tableList = null;
                try {
                    tableList = bea.extract(area);
                } catch (Exception e) {
                    log.info("rectangle extract table fail.");
                    continue;
                }
                // 如果每页有多个表格，解析每一个table
                for (Table table : tableList) {
                    for (int i = 0; i < table.getRowCount(); i++) {
                        List<String> cellList = new ArrayList<>();//一条记录，每个单元格占一个元素
                        for (int j = 0; j < table.getColCount(); j++) {
                            cellList.add(table.getCell(i, j).getText(false));
                        }
                        if (cellList.get(0).contains("说明:")) {
                            break;
                        }
                        if (StringUtils.containsAny(cellList.get(0), "金额合计", "申报日期")) {
                            continue;
                        }
                        rowList.add(cellList);
                    }
                }

            }
            return rowList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public List<IITTran> parseIITTransNew(String filePath, String pdfPassword) {
        List<IITTran> iitTrans = new ArrayList<>();
        List<List<String>> tranFieldsList = parseFileToRowList(filePath, pdfPassword);


        for (int i = 0; i < tranFieldsList.size(); i++) {
            List<String> rows = tranFieldsList.get(i);
            System.out.println(StringUtils.join(rows, ","));
            if (tranFieldsList.get(i).size() == 6) {

                // 申报日期 实缴(退)金额 连在一起用例
                // 2024.03.13 0.00
                // 适配申报日期 实缴(退)金额 入（退）库日期 连在一起用例
                // 2025.02.18 75.53 2025.02.20
                if (rows.get(0).matches("\\d{4}.\\d{2}.\\d{2}\\s\\d+.*")) {
                    IITTran iitTran = new IITTran();
                    String[] strs = rows.get(0).split(" ");
                    if (strs.length == 2) {
                        iitTran.setDeclarationDate(strs[0]);
                        iitTran.setPaidInOutAmount(strs[1]);
                        iitTran.setStockInOutDate(rows.get(1));
                    } else if (strs.length == 3) {
                        iitTran.setDeclarationDate(strs[0]);
                        iitTran.setPaidInOutAmount(strs[1]);
                        iitTran.setStockInOutDate(strs[2]);
                    }
                    iitTran.setIncomeItem(rows.get(2));
                    String[] strs1 = rows.get(3).split(" ");
                    // 适配 税款所属期 入库税务机关 连在一起
                    // ,2025.01 国家税务总局济南市市中区
                    if (strs1.length == 2) {
                        iitTran.setTaxPeriod(strs1[0]);
                        rows.set(4, strs1[1]);
                        String stockInTaxAuthority = rows.get(4);
                        if (i < tranFieldsList.size() - 1 && StringUtils.isNotBlank(tranFieldsList.get(i + 1).get(3)) && StringUtils.isBlank(tranFieldsList.get(i + 1).get(0))) {
                            stockInTaxAuthority += tranFieldsList.get(i + 1).get(3);
                        }
                        iitTran.setStockInTaxAuthority(stockInTaxAuthority);
                    } else {
                        iitTran.setTaxPeriod(rows.get(3));
                        String stockInTaxAuthority = rows.get(4);
                        if (StringUtils.isBlank(stockInTaxAuthority)) {
                            if (i > 0 && StringUtils.isNotBlank(tranFieldsList.get(i - 1).get(3)) && StringUtils.isBlank(tranFieldsList.get(i - 1).get(0))) {
                                stockInTaxAuthority = tranFieldsList.get(i - 1).get(3);
                            }
                            if (i < tranFieldsList.size() - 1 && StringUtils.isNotBlank(tranFieldsList.get(i + 1).get(3)) && StringUtils.isBlank(tranFieldsList.get(i + 1).get(0))) {
                                stockInTaxAuthority += tranFieldsList.get(i + 1).get(3);
                            }
                        }
                        iitTran.setStockInTaxAuthority(stockInTaxAuthority);
                    }

                    iitTran.setComment(rows.get(5));

                    iitTrans.add(iitTran);
                } else {
//                        System.out.println(StringUtils.join(rows, ","));
                }
            } else {
//                    System.out.println(StringUtils.join(rows, ","));
            }
        }

        try {
            resetIncomeItemForSpecialCase(iitTrans);
        } catch (Exception e) {
            log.info("resetIncomeItemForSpecialCase exception");
        }

        return iitTrans;
    }

    public List<IITTran> parseIITTrans(String filePath, String pdfPassword) {
        List<IITTran> finalIitTrans = new ArrayList<>();
        List<IITTran> iitTrans = new ArrayList<>();

        String transText = parseTransToText(filePath, pdfPassword);
        if (StringUtils.isBlank(transText)) {
            return iitTrans;
        }

        List<List<String>> tranFieldsList = parseTransTextToTranFieldsList(transText);

        for (int i = 0; i < tranFieldsList.size(); i++) {
            if (StringUtils.isNotBlank(tranFieldsList.get(i).get(0))) {
                if (StringUtils.equals(tranFieldsList.get(i).get(0), "申报⽇期")) continue;
                // 申报⽇期 | 实缴(退)⾦额 | ⼊(退)库⽇期 | 所得项⽬ | 税款所属期 | ⼊库税务机关
                // 申报⽇期 | 实缴(退)⾦额⼊(退)库⽇期 | 所得项⽬ | 税款所属期 | ⼊库税务机关 | 备注
                if (tranFieldsList.get(i).size() == 6) {
                    IITTran iitTran = new IITTran();
                    iitTran.setDeclarationDate(tranFieldsList.get(i).get(0));
                    // 实缴(退)⾦额 ⼊(退)库⽇期两个col粘在一起
                    if (tranFieldsList.get(i).get(1).matches("[-]?(\\d+.\\d{2})((\\d{4}.\\d{2}.\\d{2})|-)")) {
                        Pair<String, String> pair = parsePaidInOutAmountAndStockInOutDate(tranFieldsList.get(i).get(1));
                        iitTran.setPaidInOutAmount(pair.getLeft());
                        iitTran.setStockInOutDate(pair.getRight());

                        iitTran.setIncomeItem(tranFieldsList.get(i).get(2));
                        iitTran.setTaxPeriod(tranFieldsList.get(i).get(3));
                        iitTran.setStockInTaxAuthority(formatStockInTaxAuthority(tranFieldsList.get(i).get(4)));
                        iitTran.setComment(tranFieldsList.get(i).get(5));
                    }
                    // 备注为空
                    else if (tranFieldsList.get(i).get(1).matches("[-]?(\\d+.\\d{2})")) {
                        iitTran.setPaidInOutAmount(tranFieldsList.get(i).get(1));
                        iitTran.setStockInOutDate(tranFieldsList.get(i).get(2));
                        iitTran.setIncomeItem(tranFieldsList.get(i).get(3));
                        iitTran.setTaxPeriod(tranFieldsList.get(i).get(4));
                        iitTran.setStockInTaxAuthority(formatStockInTaxAuthority(tranFieldsList.get(i).get(5)));
                    }
                    iitTrans.add(iitTran);
                }
                // 申报⽇期 | 实缴(退)⾦额 | ⼊(退)库⽇期 | 所得项⽬ | 税款所属期 | ⼊库税务机关 | 备注
                else if (tranFieldsList.get(i).size() == 7) {
                    IITTran iitTran = new IITTran();
                    iitTran.setDeclarationDate(tranFieldsList.get(i).get(0));
                    iitTran.setPaidInOutAmount(tranFieldsList.get(i).get(1));
                    iitTran.setStockInOutDate(tranFieldsList.get(i).get(2));
                    iitTran.setIncomeItem(tranFieldsList.get(i).get(3));
                    iitTran.setTaxPeriod(tranFieldsList.get(i).get(4));
                    iitTran.setStockInTaxAuthority(formatStockInTaxAuthority(tranFieldsList.get(i).get(5)));
                    iitTran.setComment(tranFieldsList.get(i).get(6));
                    iitTrans.add(iitTran);
                    //申报⽇期;实缴(退)⾦额;⼊(退)库⽇期;所得项⽬;税款所属期;⼊库税务机关;;备注
                } else if (tranFieldsList.get(i).size() == 8) {
                    IITTran iitTran = new IITTran();
                    iitTran.setDeclarationDate(tranFieldsList.get(i).get(0));
                    iitTran.setPaidInOutAmount(tranFieldsList.get(i).get(1));
                    iitTran.setStockInOutDate(tranFieldsList.get(i).get(2));
                    iitTran.setIncomeItem(tranFieldsList.get(i).get(3));
                    iitTran.setTaxPeriod(tranFieldsList.get(i).get(4));
                    iitTran.setStockInTaxAuthority(formatStockInTaxAuthority(tranFieldsList.get(i).get(5)));
                    iitTran.setComment(tranFieldsList.get(i).get(7));
                    iitTrans.add(iitTran);
                }
            } else {
                if (tranFieldsList.get(i).size() == 6) {
                    // 过滤掉第一行 ";;;;;国家税务总局宁乡经济技术" 这种case
                    if (i > 0) {
                        // 实缴(退)⾦额 ⼊(退)库⽇期两个col粘在一起
                        if (tranFieldsList.get(i - 1).get(1).matches("[-]?(\\d+.\\d{2})((\\d{4}.\\d{2}.\\d{2})|-)")) {
                            try {
                                if (StringUtils.isNotBlank(tranFieldsList.get(i).get(2))) {
                                    iitTrans.get(iitTrans.size() - 1).setIncomeItem(iitTrans.get(iitTrans.size() - 1).getIncomeItem() + tranFieldsList.get(i).get(2));
                                }
                            } catch (Exception e) {
                                log.info("reset IncomeItem exception");
                            }
                            try {
                                if (StringUtils.isNotBlank(tranFieldsList.get(i).get(4))) {
                                    iitTrans.get(iitTrans.size() - 1).setStockInTaxAuthority(iitTrans.get(iitTrans.size() - 1).getStockInTaxAuthority() + tranFieldsList.get(i).get(4));
                                }
                            } catch (Exception e) {
                                log.info("reset StockInTaxAuthority exception");
                            }
                        }
                        // 备注为空
                        else if (tranFieldsList.get(i - 1).get(1).matches("[-]?(\\d+.\\d{2})")) {
                            try {
                                if (StringUtils.isNotBlank(tranFieldsList.get(i).get(3))) {
                                    iitTrans.get(iitTrans.size() - 1).setIncomeItem(iitTrans.get(iitTrans.size() - 1).getIncomeItem() + tranFieldsList.get(i).get(3));
                                }
                            } catch (Exception e) {
                                log.info("reset IncomeItem exception");
                            }
                            try {
                                if (StringUtils.isNotBlank(tranFieldsList.get(i).get(5))) {
                                    iitTrans.get(iitTrans.size() - 1).setStockInTaxAuthority(iitTrans.get(iitTrans.size() - 1).getStockInTaxAuthority() + tranFieldsList.get(i).get(5));
                                }
                            } catch (Exception e) {
                                log.info("reset StockInTaxAuthority exception");
                            }
                        }
                    }
                } else if (tranFieldsList.get(i).size() == 7 || tranFieldsList.get(i).size() == 8) {
                    try {
                        if (StringUtils.isNotBlank(tranFieldsList.get(i).get(3))) {
                            iitTrans.get(iitTrans.size() - 1).setIncomeItem(iitTrans.get(iitTrans.size() - 1).getIncomeItem() + tranFieldsList.get(i).get(3));
                        }
                    } catch (Exception e) {
                        log.info("reset IncomeItem exception");
                    }
                    try {
                        if (StringUtils.isNotBlank(tranFieldsList.get(i).get(5))) {
                            iitTrans.get(iitTrans.size() - 1).setStockInTaxAuthority(iitTrans.get(iitTrans.size() - 1).getStockInTaxAuthority() + tranFieldsList.get(i).get(5));
                        }
                    } catch (Exception e) {
                        log.info("reset StockInTaxAuthority exception");
                    }
                }
            }
        }

        try {
            // 个税表格 记录以外的行(比如以"金额合计" "特别说明"等开头的行)
            iitTrans.forEach(iitTran -> {
                if (StringUtils.isNotBlank(iitTran.getTaxPeriod())) {
                    finalIitTrans.add(iitTran);
                }
            });

            resetIncomeItemForSpecialCase(finalIitTrans);
        } catch (Exception e) {
            log.info("resetIncomeItemForSpecialCase exception");
        }

        return finalIitTrans;
    }

    // 解析  实缴(退)⾦额 ⼊(退)库⽇期 两个字段
    private Pair<String, String> parsePaidInOutAmountAndStockInOutDate(String paidInOutAmountAndStockInOutDate) {
        Pair<String, String> pair = Pair.of("", "");
        if (StringUtils.isNotBlank(paidInOutAmountAndStockInOutDate)) {
            // 362.692021.09.16  0.00-  -151.462022.06.17
            Pattern pattern = Pattern.compile("[-]?(\\d+.\\d{2})");
            Matcher matcher = pattern.matcher(paidInOutAmountAndStockInOutDate);
            if (matcher.find()) {
                String paidInOutAmount = matcher.group();
                String stockInOutDate = paidInOutAmountAndStockInOutDate.substring(matcher.end());
                pair = Pair.of(paidInOutAmount, stockInOutDate);
            }
        }
        return pair;
    }

    private void resetIncomeItemForSpecialCase(List<IITTran> iitTrans) {
        for (IITTran iitTran : iitTrans) {
            if (StringUtils.equals("利息、利股所息得、红", iitTran.getIncomeItem())) {
                iitTran.setIncomeItem("利息、股息、红利所得");
            } else if ((StringUtils.equals("个⼈房屋得出租所", iitTran.getIncomeItem()))) {
                iitTran.setIncomeItem("个⼈房屋出租所得");
            } else if ((StringUtils.equals("个⼈房屋得转让所", iitTran.getIncomeItem()))) {
                iitTran.setIncomeItem("个⼈房屋转让所得");
            } else if ((StringUtils.equals("特许权使得⽤费所", iitTran.getIncomeItem()))) {
                iitTran.setIncomeItem("特许权使⽤费所得");
            } else if (StringUtils.equals("其他财产得租赁所", iitTran.getIncomeItem())) {
                iitTran.setIncomeItem("其他财产租赁所得");
            }
        }
    }

    private String formatStockInTaxAuthority(String stockInTaxAuthority) {

        String formatStr = stockInTaxAuthority;

        try {
            //入库税务机关，一行最多显示12个汉字，超过12个就会换行，只有超过12个字才会需要调整
            //国成家都税管务理总委局员四会川税天务府局新区
            if (stockInTaxAuthority.length() <= 12 || stockInTaxAuthority.length() > 24) {
                return formatStr;
            }

            // 下面就是显示两行的情况
            StringBuilder sb = new StringBuilder(stockInTaxAuthority);
            int charNumInNewLine = stockInTaxAuthority.length() - 12;
            for (int i = 0; i < charNumInNewLine; i++) {
                sb.append(stockInTaxAuthority.charAt(2 * i + 1));
            }
            for (int i = 1; i <= charNumInNewLine; i++) {
                sb.deleteCharAt(i);
            }
            formatStr = sb.toString();
        } catch (Exception e) {
            log.error("formatStockInTaxAuthority failed, stockInTaxAuthority: {}", stockInTaxAuthority, e);
            e.printStackTrace();
        }

        return formatStr;
    }

    private void doAlert(String daId, IIT iit) {
        log.info("doAlert started daId: {}", daId);
        //加入字段告警
        if (StringUtils.isBlank(iit.getRecordPeriod())) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iit recordPeriod is empty");
            throw new RuntimeException("the tax pdf format maybe changed");
        }
        if (StringUtils.isBlank(iit.getTaxpayerName())) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iit taxpayerName is empty");
            throw new RuntimeException("the tax pdf format maybe changed");
        }
        if (StringUtils.isBlank(iit.getTaxpayerIdNo())) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iit taxpayerIdNo is empty");
            throw new RuntimeException("the tax pdf format maybe changed");
        }
        if (StringUtils.isBlank(iit.getIdCardType())) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iit idCardType is empty");
            throw new RuntimeException("the tax pdf format maybe changed");
        }
        if (StringUtils.isBlank(iit.getIdNo())) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iit idNo is empty");
            throw new RuntimeException("the tax pdf format maybe changed");
        }
        if (StringUtils.isBlank(iit.getAmountUnit())) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iit amountUnit is empty");
            throw new RuntimeException("the tax pdf format maybe changed");
        }
        if (StringUtils.isBlank(iit.getIssueDate())) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iit issueDate is empty");
            throw new RuntimeException("the tax pdf format maybe changed");
        }

        List<IITTran> iitTrans = iit.getIitTrans();

        for (IITTran iitTran : iitTrans) {
            if (StringUtils.isBlank(iitTran.getDeclarationDate())) {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iitTran declarationDate is empty");
                throw new RuntimeException("the tax pdf format maybe changed");
            }
            if (StringUtils.isBlank(iitTran.getPaidInOutAmount())) {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iitTran paidInOutAmount is empty");
                throw new RuntimeException("the tax pdf format maybe changed");
            }
            if (StringUtils.isBlank(iitTran.getIncomeItem())) {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iitTran incomeItem is empty");
                throw new RuntimeException("the tax pdf format maybe changed");
            }
            if (StringUtils.isBlank(iitTran.getTaxPeriod())) {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iitTran taxPeriod is empty");
                throw new RuntimeException("the tax pdf format maybe changed");
            }
            if (StringUtils.isBlank(iitTran.getStockInTaxAuthority())) {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iitTran stockInTaxAuthority is empty");
                throw new RuntimeException("the tax pdf format maybe changed");
            }
            if (StringUtils.isBlank(iitTran.getStockInOutDate())) {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), "", "", "", "iitTran stockInOutDate is empty");
                throw new RuntimeException("the tax pdf format maybe changed");
            }
        }

        log.info("doAlert completed daId: {}", daId);
    }


    public static void main(String[] args) throws IOException {

//        String pdfFilePath = "D:\\data\\file\\taxeat\\zd4lxrz01573230457355710464_a4b1045039c62069c25b71004f453a97_tax_nsjl-200811.pdf";
//        String jsonFilePath = "D:\\data\\file\\iit\\zd4lxrz01573230457355710464_a4b1045039c62069c25b71004f453a97_tax_nsjl-200811json";
//        String passWord = "200811";

        String pdfFilePath = "D:\\data\\file\\taxeat\\025518.pdf";
        String jsonFilePath = "D:\\data\\file\\iit\\zd4lxrz01573230457355710464_a4b1045039c62069c25b71004f453a97_tax_nsjl-200811json";
        String passWord = "025518";
        File jsonFile = new File(jsonFilePath);
        IITPdfParser iitParser = new IITPdfParser();
        ResponseData<String> responseData = iitParser.parseIITPdfToJson("dd", pdfFilePath, passWord);
//		FileUtils.write(jsonFile, responseData.getData(), "UTF-8");
        System.out.println(responseData.getData());

//		jsonFile.createNewFile();

//		log.info(iitParser.formatStockInTaxAuthority("国税家务税局务总局成都市⾦⽜区"));
    }

}
